package akka.shoppingcart.domain

import akka.shoppingcart.domain.ShoppingCartEvent.ItemAdded

data class ShoppingCart(
    val cartId: String,
    val items: List<LineItem>,
    val checkedOut: Boolean = false
) {
  fun onItemAdded(itemAdded: ItemAdded): ShoppingCart {
    val lineItem = updateItem(itemAdded.item)
    val lineItems = removeItemByProductId(itemAdded.item.productId)
    return copy(items = (lineItems + lineItem).sortedBy { it.productId })
  }

  private fun updateItem(item: LineItem) =
      findItemByProductIdOrNull(item.productId)?.let { li ->
        li.copy(quantity = li.quantity + item.quantity)
      } ?: item

  private fun removeItemByProductId(productId: String) = items.filter { it.productId != productId }

  fun findItemByProductIdOrNull(productId: String?) =
      items.firstOrNull { it.productId == productId }
}

data class LineItem(val productId: String, val name: String, val quantity: Int)
